package com.example.blog.util.Excel;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.OutputStream;
import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;


public class ExportExcelUtils {


    public static void exportExcel(List<?> list, String[] headers, String sheetName, OutputStream out) throws Exception {
        if (list == null || list.isEmpty()) {
            throw new Exception("数据集合为空");
        }
        // 创建工作簿
        Workbook workbook = new XSSFWorkbook();
        // 创建工作表
        Sheet sheet = workbook.createSheet(sheetName);
        // 创建表头行
        Row row = sheet.createRow(0);
        for (int i = 0; i < headers.length; i++) {
            // 创建单元格并设置表头值
            Cell cell = row.createCell(i);
            cell.setCellValue(headers[i]);
        }
        // 遍历数据集合，创建数据行
        for (int i = 0; i < list.size(); i++) {
            row = sheet.createRow(i + 1);
            Object obj = list.get(i);
            if (obj == null) {
                continue;
            }
            // 获取对象的所有属性
            Field[] fields = obj.getClass().getDeclaredFields();
            for (int j = 0; j < fields.length; j++) {
                // 获取属性值并创建单元格
                Field field = fields[j];
                field.setAccessible(true);
                Object value = field.get(obj);
                Cell cell = row.createCell(j);
                // 根据数据类型进行处理
                if (value == null) {
                    cell.setCellValue("");
                } else if (value instanceof String) {
                    cell.setCellValue((String) value);
                } else if (value instanceof Integer) {
                    cell.setCellValue((Integer) value);
                } else if (value instanceof Double) {
                    cell.setCellValue((Double) value);
                } else if (value instanceof Boolean) {
                    cell.setCellValue((Boolean) value);
                } else if (value instanceof Date) {
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    cell.setCellValue(sdf.format((Date) value));
                } else {
                    cell.setCellValue(value.toString());
                }
            }
        }
        // 写入文件
        workbook.write(out);
        workbook.close();
    }


}